package com.lly.songhigh.mediaplayer;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Created by 李海龙 on 15/10/28.
 */
public class MyMediaPlayer extends SurfaceView {

    private MediaPlayer mediaPlayer;
    private Handler handler;

    public MyMediaPlayer(Context context) {
        super(context);
        init();
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public MyMediaPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {//初始化
        mediaPlayer = new MediaPlayer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (mediaPlayer.isPlaying()) {
                        Message message = new Message();
                        message.what = 1;//代表刷新 UI
                        message.arg1 = mediaPlayer.getCurrentPosition();
                        handler.sendMessage(message);
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }


    public int getMax() {
        return mediaPlayer.getDuration();
    }

    public void setUrl(String url) {//设置url
        Log.i("Sysout", "---->" + url);
        mediaPlayer.reset();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            //mediaPlayer.release();
            try {
                //mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(url);

                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            try {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    //播放音乐
    public void play() {
        mediaPlayer.setDisplay(getHolder());
        mediaPlayer.start();
    }

    public void stop() {
        mediaPlayer.stop();
    }

    public void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }
}
